package com.tanglon.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.tanglon.domain.ResponseResult;
import com.tanglon.domain.dto.AddUserDTO;
import com.tanglon.domain.dto.UpdateUserDTO;
import com.tanglon.domain.entity.Category;
import com.tanglon.domain.entity.User;
import com.tanglon.domain.vo.ExcelCategoryVo;
import com.tanglon.enums.AppHttpCodeEnum;
import com.tanglon.mapper.UserMapper;
import com.tanglon.service.UserRoleService;
import com.tanglon.service.UserService;
import com.tanglon.utils.BeanCopyUtils;
import com.tanglon.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    
    @GetMapping("/list")
    public ResponseResult userList(Integer pageNum, Integer pageSize,
                                   String userName , String phonenumber, String status) {

        return userService.userList(pageNum,pageSize,userName,phonenumber,status);
    }


    @PostMapping
    public ResponseResult addUser(@RequestBody AddUserDTO addUserDTO) {
        return userService.addUser(addUserDTO);
    }


    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable Integer id) {
        userService.removeById(id);
        userRoleService.removeById(id);
        return ResponseResult.okResult();
    }

    @GetMapping("/{id}")
    public ResponseResult getUserDetail(@PathVariable Long id) {
        return userService.getUserDetail(id);
    }


    @PutMapping
    public ResponseResult updateUser(@RequestBody UpdateUserDTO updateUserDTO) {
        return userService.updateUser(updateUserDTO);
    }


    @PostMapping("/import")
    public void importUser(@RequestParam("file") MultipartFile file)throws Exception {

    }

    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("用户.xlsx",response);
            //获取需要导出的数据
            List<User> categoryVos = userService.list();

            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("用户导出")
                    .doWrite(excelCategoryVos);

        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
}
